/* eslint-disable */
import React, { useEffect, useState } from 'react';
import { connect } from 'dva';
import { Table, Divider, Button, Card, Form, Row, Col, Input, Select, Spin, Modal, Popover, message } from 'antd';
import * as echarts from 'echarts';
import CounterpartyChooseRadio from "../../common/CounterpartyChooseRadio";
import OrganizationChooseRadio from "../../common/OrganizationChooseRadio";
import CreditFileManagementModal from '../creditFileManagement/CreditFileManagementModal';
import ModelSelection from '../../common/ModelSelection';
import AttachmentUploadModal from '../../common/AttachmentUploadModal';
import TablePagination from '../../common/TablePagination';
import img from "../../../assets/logo-loading.gif"
import styles from './CreditEvaluation.less';
import { valueToPercent, formatNoFixed, emptyText, reservedDecimalPlace, debounce } from '../../../utils/commonUtil';
import {
  getDetail, getDetailByCreditEvaluationId, getHistoryEvaluationResult, getHistoryEvaluationResultNotPage, getHistoryDataLastTime, getCreditDataByCompanyName,
  getCreditData, addCreditEvaluation, getEvaluation, getByCode, getIndicatorPoolsById, getIndicatorDetail
} from '../../../services/credit/creditEvaluationService';
import { EllipsisOutlined, ExclamationCircleOutlined, SearchOutlined } from '@ant-design/icons';
import moment from 'moment';
const { Option } = Select;
const FormItem = Form.Item;
const { Search } = Input;

const CreditEvaluationCreate = (props) => {

  const { dispatch, creditEvaluationModel, globalModel, onCancel, examinationApprovalStatus, creditEvaluationInfoData, orgChooseList, operateType, creditEvaluation,
    customerTypeFlag, creditEvaluationFlagTrue } = props;
  const { organizationChooseRadioPageSize, organizationChooseRadioTotal, organizationChooseRadioLoading, organizationChooseRadioList, organizationChooseRadioCurrentPage,
    selectedRows, counterpartyPageSize, counterpartyTotal, counterpartyModalVisible, counterpartyLoading, counterpartyList, counterpartyCurrentPage, selectedRowKeys,
    organizationChooseRadioVisible, modelList, modelFlag, modelFilterModalerVisible, modelLoading, modelListData, searchParams, modelCurrentPage, modelPageSize,
    ownerShipInstitution, ownerShipInstitutionCode, attachmentUploadModalLoading, masterDataCode, attachmentUploadModalList, attachmentUploadModalVisible, menuData,
    modelTotal, } = creditEvaluationModel
  const { userInfo } = globalModel
  const [buttonDisabled, setButtonDisabled] = useState(true)
  const [form] = Form.useForm();
  const { getFieldsValue, validateFields, setFieldsValue, resetFields } = form;
  const [creditFiles, useCreditFiles] = useState(false)
  const [spinFlag, useSpinFlag] = useState(false)
  const [historicalPList, useHistoricalPList] = useState([])
  const [historicalList, useHistoricalList] = useState([])
  const [historicalTotal, useHistoricalTotal] = useState(0)
  const [historicalCurrentPage, useHistoricalCurrentPage] = useState(1)
  const [historicalPageSize, useHistoricalPageSize] = useState(10)
  const [detailList, useDetailList] = useState({})
  const [historicalLoading, useHistoricalLoading] = useState(false)
  const [disabledFlag, useDisabledFlag] = useState(false)
  const [referenceDataFlag, useReferenceDataFlag] = useState(false)
  const [indicatorScoreResultVoList, useIndicatorScoreResultVoList] = useState([])
  const [optionList, useOptionList] = useState([])
  const [indicatorValueFlag, useIndicatorValueFlag] = useState(false)

  const styleFlag = {
    zoom: 1 / document.body.style.zoom,
    transform: 'scale(' + document.body.style.zoom + ')',
    transformOrigin: "0%0%",
    width: 1 / document.body.style.zoom * 100 + '%',
    height: 1 / document.body.style.zoom * 100 + '%'
  }

  const menuProcessing = (value) => {
    let count = menuData.filter(item => item.indexOf(value) !== -1)
    return count.length === 0
  }

  let creditEvaluationAdjustmentList = detailList.creditEvaluationAdjustmentList ? detailList.creditEvaluationAdjustmentList : []
  let modelScoreResult = detailList.modelScoreResult ? detailList.modelScoreResult : {}
  let indicatorAdjustmentList = []

  creditEvaluationAdjustmentList.forEach(item => {
    item.indicatorAdjustmentList.map((i, index) => {
      if (index === 0) {
        i.rowSpan = item.indicatorAdjustmentList.length
      } else {
        i.rowSpan = 0
      }
      return i
    })
    indicatorAdjustmentList = indicatorAdjustmentList.concat(item.indicatorAdjustmentList)
  })

  const examinationApprovalStatusOptions = examinationApprovalStatus.map(item => <Option key={item.dictSubCode} value={item.dictSubCode}>{item.dictValue}</Option>);

  const informationEvaluationIndex = [
    { title: '指标', dataIndex: 'indicatorName', key: 'indicatorName', },
    {
      title: '取值', dataIndex: 'indicatorValue', key: 'indicatorValue',
      render: (text, record, index) => {
        if (record.indicatorType == '数值型') {
          return <Input value={text} onChange={(e) => { onIndicatorsChange(record, e.target.value, index) }}
            disabled={menuProcessing('_indicatorEdit') || indicatorValueFlag} />
        } else if (record.indicatorType == '逻辑型') {
          return <Select value={text} onChange={(e) => { onIndicatorsChange(record, e, index) }} style={{ width: '100%' }}
            disabled={menuProcessing('_indicatorEdit') || indicatorValueFlag}>
            <Option value='1'>是</Option>
            <Option value='0'>否</Option>
          </Select>
        } else if (record.indicatorType == '字符型') {
          return <Select value={text} onChange={(e) => { onIndicatorsChange(record, e, index) }} style={{ width: '100%' }}
            disabled={menuProcessing('_indicatorEdit') || indicatorValueFlag}>
            {optionList.map(item => item.symbol == record.category && <Option key={item.dictSubCode} value={item.dictValue}>{item.dictValue}</Option>)}
          </Select>
        }
      },
    },
    { title: '数据来源', dataIndex: 'dataSources', key: 'dataSources', },
    {
      title: '权重(%)', dataIndex: 'weight', key: 'weight',
      render: (text, row,) => <span>{reservedDecimalPlace(valueToPercent(text), 2)}%</span>
    },
    {
      title: '该项最终得分', dataIndex: 'finalScore', key: 'finalScore',
      render: (text, row,) => <span>{getFieldsValue().assessmentStatus == "credit_evaluation_complete" ? reservedDecimalPlace(text, 4, true) : ''}</span>
    },
  ];
  const historicalAssessmentResults = [
    { title: '评估模型', dataIndex: 'modelName', key: 'modelName', },
    {
      title: '客户信用评估综合得分', dataIndex: 'evaluationScore', key: 'evaluationScore',
      render: (text, row,) => <span>{reservedDecimalPlace(text, 2, true)}</span>
    },
    { title: '客户信用评估等级', dataIndex: 'evaluationLevel', key: 'evaluationLevel', },
    {
      title: '评估时间', dataIndex: 'evaluationDate', key: 'evaluationDate',
      render: (text, row,) => row.flag == 1 ? <span style={{ color: "#e64552" }}>{text}</span> : <span>{text}</span>,
    },
    { title: '评估人', dataIndex: 'evaluationName', key: 'evaluationName', },
  ];
  const adjustmentEvaluationResults = [
    { title: '触发指标', dataIndex: 'indicatorName', key: 'indicatorName', },
    {
      title: '指标规则', dataIndex: 'indicatorType', key: 'indicatorType',
      render: (text, row,) => {
        if (text === "字符型") {
          return <span>{row.charValue}</span>;
        } else if (text === "布尔型") {
          return <span>{row.booleanValue}</span>;
        } else if (text === "数值型") {
          return <span>
            {((String(row.numMin) == "null" || String(row.numMin) == "" || String(row.numMin) == "undefined") &&
              !(String(row.numMax) == "null" || String(row.numMax) == "")) && "小于 "}
            {!(String(row.numMin) == "null" || String(row.numMin) == "") && (String(row.numMax) == "null" || String(row.numMax) == "") && "大于 "}
            {!(String(row.numMin) == "null" || String(row.numMin) == "") && row.numMin}
            {(!(String(row.numMin) == "null" || String(row.numMin) == "" || String(row.numMin) == "undefined") &&
              !(String(row.numMax) == "null" || String(row.numMax) == "")) && "--"}
            {!(String(row.numMax) == "null" || String(row.numMax) == "") && row.numMax}
          </span>
        }
      },
    },
    { title: '取值', dataIndex: 'indicatorValue', key: 'indicatorValue', },
    {
      title: '调整结果', dataIndex: 'adjustmentType', key: 'adjustmentType',
      render: (text, row, index) => {
        let children = null
        if (text == 2) {
          children = "评估等级升二级"
        } else if (text == 1) {
          children = "评估等级升一级"
        } else if (text == 0) {
          children = "不予评级"
        } else if (text == -1) {
          children = "评估等级降一级"
        } else if (text == -2) {
          children = "评估等级降二级"
        }
        return {
          children,
          props: {
            rowSpan: row.rowSpan
          },
        };
      },
    },
  ];

  const onIndicatorsChange = (record, value, index) => {
    let indexFlag = null
    indicatorScoreResultVoList.forEach((item, index) => {
      if (item.modelId == record.modelId) {
        indexFlag = index
      }
    })
    indicatorScoreResultVoList[indexFlag].indicatorScoreResultList[index].indicatorValue = value
    useIndicatorScoreResultVoList(JSON.parse(JSON.stringify(indicatorScoreResultVoList)))
  }

  const onGetDetail = (data) => {
    getDetail({ creditEvaluationId: data.id }).then(res => {
      resetFields()
      setFieldsValue(res.data)
      if (!(res.data.assessmentStatus == "credit_evaluation_new" || res.data.assessmentStatus == "credit_evaluation_failure")) {
        useDisabledFlag(true)
      }
      if (res.data.assessmentStatus !== "credit_evaluation_new") {
        useReferenceDataFlag(true)
      }
      if (res.data.assessmentStatus == "credit_evaluation_complete" || res.data.assessmentStatus == "credit_evaluation_midway") {
        useIndicatorValueFlag(true)
      }
      if (res.data.assessmentStatus == "credit_evaluation_complete" || res.data.assessmentStatus == "credit_evaluation_failure") {
        getDetailByCreditEvaluationId({ creditEvaluationId: data.id }).then(res => {
          useDetailList(res.data)
          useIndicatorScoreResultVoList(res.data ? res.data.indicatorScoreResultVoList : [])
          onGetByCode(res.data ? res.data.indicatorScoreResultVoList : [])
        })
        useHistoricalLoading(true)
        onGetHistoryEvaluationResult({ creditEvaluationId: data.id, currentPage: 1, pageSize: 10 })
        getHistoryEvaluationResultNotPage({ creditEvaluationId: data.id }).then(res => { useHistoricalPList(res.data) })
      } else {
        getIndicatorDetail({ id: data.id, sign: res.data.sign, assessmentModelId: res.data.assessmentModelId, }).then(res => {
          let indicatorScoreResultVoList = res.data ? res.data : []
          let list = []
          indicatorScoreResultVoList.forEach(item => {
            item.modelWeight = item.modelWeight ? item.modelWeight : 1
            list = list.concat(item.indicatorScoreResultList)
          })
          let value = list.map(item => item.indicatorId).join(',')
          getIndicatorPoolsById({ ids: value }).then(prop => {
            indicatorScoreResultVoList.forEach(item => {
              item.indicatorScoreResultList.forEach(i => {
                let listClonre = prop.data.filter(t => t.pid == i.indicatorId)
                if (listClonre.length > 0) {
                  i.category = listClonre[0].category
                  i.indicatorType = listClonre[0].type
                }
              })
            })
            useIndicatorScoreResultVoList(indicatorScoreResultVoList)
            onGetByCode(indicatorScoreResultVoList)
          })
        })
      }
      dispatch({
        type: "creditEvaluationModel/updateState", payload: {
          ownerShipInstitution: res.data.affiliatedInstitutionName, ownerShipInstitutionCode: res.data.affiliatedInstitution,
        }
      });
    })
  }

  const onGetByCode = (data) => {
    let list = []
    data.forEach(item => {
      list = list.concat(item.indicatorScoreResultList)
    })
    let value = list.map(item => item.category).join(',')
    getByCode({ dictValue: value }).then(res => {
      useOptionList(res.data ? res.data : [])
    })
  }

  const onGetHistoryEvaluationResult = (data) => {
    getHistoryEvaluationResult(data).then(res => {
      useHistoricalList(res.data.records)
      useHistoricalTotal(res.data.total)
      useHistoricalCurrentPage(res.data.currentPage)
      useHistoricalPageSize(res.data.pageSize)
      useHistoricalLoading(false)
    })
  }

  const onAdd = () => {
    validateFields().then(values => {
      values.assessmentType = "单客户评估"
      if (indicatorScoreResultVoList.length > 0) {
        let indicatorScoreResultVoListClone = []
        indicatorScoreResultVoList.forEach(item => {
          indicatorScoreResultVoListClone = indicatorScoreResultVoListClone.concat(item.indicatorScoreResultList)
        })
        values.indicatorScoreResultList = indicatorScoreResultVoListClone
      }
      addCreditEvaluation(values).then(res => {
        if (res.code == 200 || res.code == 201) {
          message.info("新增成功！");
          setButtonDisabled(false)
          dispatch({ type: 'creditEvaluationModel/getListDatas', payload: {} });
          onGetDetail({ id: res.data instanceof Array && res.data[0] ? res.data[0].indicatorScoreResultList[0].creditEvaluationId : res.data })
        } else {
          message.info("新增失败！");
        }
        useSpinFlag(false)
      })
    }).catch(error => { });
  }

  useEffect(() => {
    if (operateType === "add") {
      creditEvaluationInfoData.basicId = creditEvaluationInfoData.quotaAccountId
      resetFields()
      setFieldsValue(creditEvaluationInfoData)
      if (!(creditEvaluationInfoData.assessmentStatus == "credit_evaluation_new" || creditEvaluationInfoData.assessmentStatus == "credit_evaluation_failure")) {
        useDisabledFlag(true)
      }
      creditEvaluation && onChange()
      creditEvaluation && dispatch({
        type: "creditEvaluationModel/updateState", payload: {
          idFlag: null, modelFlag: false, detailList: {},
          ownerShipInstitution: creditEvaluationInfoData.affiliatedInstitutionName, ownerShipInstitutionCode: creditEvaluationInfoData.affiliatedInstitution,
        }
      });
    } else if (operateType === "view") {
      setButtonDisabled(false)
      onGetDetail(creditEvaluationInfoData)
    }
  }, [operateType])

  useEffect(() => {
    if (modelFlag) {
      if (modelList) {
        setFieldsValue({ assessmentModelId: modelList.normalModelId, assessmentModelName: modelList.normalModelName, sign: modelList.sign })
      } else {
        setFieldsValue({ assessmentModelId: "", assessmentModelName: "", sign: "" })
      }
    }

  }, [modelFlag, modelList])

  useEffect(() => {
    const data = historicalPList.map(item => item.evaluationDate)
    historicalPList.forEach(item => item.value = item.evaluationScore)
    var myChart = echarts.getInstanceByDom(document.getElementById('history'))
    if (myChart == null) { // 如果不存在，就进行初始化
      myChart = echarts.init(document.getElementById("history"));
    }
    var option = {
      color: ["#489CC9"],
      xAxis: {
        type: 'category',
        data: data
      },
      yAxis: {
        type: 'value'
      },
      dataZoom: [{
        type: 'slider',
        show: true,
        startValue: 0,
        endValue: 12,
        height: '24',
        bottom: '5%',
        zoomLock: true,
        backgroundColor: "#F0F2FB",
        textStyle: {
          color: '#626681',
          fontFamily: 'PingFang SC',
          fontSize: '10'
        },
        fillerColor: 'rgba(1,1,1,0.1)',
        showDataShadow: true, //是否显示数据阴影 默认auto
        showDetail: true, //即拖拽时候是否显示详细数值信息 默认true
        realtime: false, //是否实时更新
        handleSize: 24, //滑动条的 左右2个滑动条的大小
        handleIcon: // 用于画手柄
          "path://M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z", // 画一个圆形
        handleStyle: {
          borderRadius: '20',
          color: '#FFFFFF',
          shadowBlur: 6,
          shadowColor: 'rgba(0, 0, 0, 0.2)',
          shadowOffsetX: 1,
          shadowOffsetY: 2,
        },
        moveHandleSize: 0
      }],
      tooltip: {
        trigger: null,
        formatter: (params) => {
          return '评估模型：' + params.data.modelName + '<br/>客户信用评估综合得分：' +
            params.data.evaluationScore + ' <br/>客户信用评估等级：' + params.data.evaluationLevel
        }
      },
      series: [{
        data: historicalPList,
        type: 'line',
        areaStyle: {
          //颜色渐变函数 前四个参数分别表示四个位置依次为左、下、右、上
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
            offset: 0,
            color: 'rgba(72,156,201,0.39)'
          }, {
            offset: 1,
            color: 'rgba(255,255,255)'
          }])

        }, //区域颜色渐变
        smooth: true
      }]
    };

    myChart.setOption(option)

  }, [historicalPList])

  const onChange = () => {
    if (getFieldsValue().masterDataCode && getFieldsValue().affiliatedInstitution) {
      dispatch({ type: "creditEvaluationModel/updateState", payload: { modelFlag: false } });
      dispatch({
        type: 'creditEvaluationModel/getModelByAffiliatedInstitution',
        payload: { affiliatedInstitution: getFieldsValue().affiliatedInstitution, masterDataCode: getFieldsValue().masterDataCode, customerTypeCode: customerTypeFlag }
      });
    }
  }

  const counterpartyChooseProps = {
    counterpartyModalVisible, counterpartyLoading, counterpartyList, counterpartyCurrentPage, counterpartyPageSize, counterpartyTotal,
    onSave: (key, rows) => {
      setFieldsValue({
        counterpartyName: rows[0].counterpartyName,
        masterDataCode: rows[0].masterDataCode,
      })
      dispatch({ type: "creditEvaluationModel/updateState", payload: { counterpartyModalVisible: false, } });
      onChange()
    },
    onCancelSon: () => {
      dispatch({ type: "creditEvaluationModel/updateState", payload: { counterpartyModalVisible: false, } });
    },
    onSearch: (searchParams) => {
      dispatch({ type: "creditEvaluationModel/updateState", payload: { searchParams } });
      dispatch({ type: 'creditEvaluationModel/getAllCreditArchive', payload: { params: { ...searchParams, affiliatedInstitution: ownerShipInstitutionCode }, } });
    },
    onReset: () => {
      if (ownerShipInstitutionCode) {
        dispatch({ type: "creditEvaluationModel/updateState", payload: { searchParams: null } });
        dispatch({ type: 'creditEvaluationModel/getAllCreditArchive', payload: { params: { affiliatedInstitution: ownerShipInstitutionCode } } });
      }
    },
    onPageChange: (currentPage, pageSize) => {
      if (ownerShipInstitutionCode) {
        dispatch({
          type: 'creditEvaluationModel/getAllCreditArchive',
          payload: { currentPage, pageSize, params: { ...searchParams, affiliatedInstitution: ownerShipInstitutionCode }, }
        });
      }
    },
    onShowSizeChange: (currentPage, pageSize) => {
      if (ownerShipInstitutionCode) {
        dispatch({
          type: 'creditEvaluationModel/getAllCreditArchive',
          payload: { currentPage, pageSize, params: { ...searchParams, affiliatedInstitution: ownerShipInstitutionCode }, }
        });
      }
    },
  }

  const tablePaginationProps = {
    total: historicalTotal,
    currentPage: historicalCurrentPage,
    pageSize: historicalPageSize,
    onPageChange: (currentPage, pageSize,) => {
      useHistoricalLoading(true)
      onGetHistoryEvaluationResult({ creditEvaluationId: getFieldsValue().id, currentPage, pageSize })
    },
    onShowSizeChange: (currentPage, pageSize,) => {
      useHistoricalLoading(true)
      onGetHistoryEvaluationResult({ creditEvaluationId: getFieldsValue().id, currentPage, pageSize })
    },
  };

  const organizationChooseRadioProps = {
    organizationChooseRadioPageSize, organizationChooseRadioTotal, organizationChooseRadioCurrentPage, organizationChooseRadioVisible,
    orgChooseList, organizationChooseRadioList, organizationChooseRadioLoading,
    organizationAdd: (key, row) => {
      setFieldsValue({
        affiliatedInstitutionName: row[0].orgName,
        affiliatedInstitution: key.join(","),
        counterpartyName: "",
        masterDataCode: '',
      })
      dispatch({
        type: "creditEvaluationModel/updateState", payload: {
          organizationChooseRadioVisible: false, orgSubModalFlag: false, ownerShipInstitution: row[0].orgName, ownerShipInstitutionCode: key.join(",")
        }
      });
    },
    onOrganizationChooseRadioCancel: () => {
      dispatch({ type: "creditEvaluationModel/updateState", payload: { organizationChooseRadioVisible: false, orgSubModalFlag: false } });
    },
    onOrganizationChooseRadioSearch: (searchParams) => {
      dispatch({ type: "creditEvaluationModel/updateState", payload: { searchParams } });
      dispatch({ type: 'creditEvaluationModel/getAllOrganizationItem', payload: { params: searchParams } });
    },
    onOrganizationChooseRadioReset: () => {
      dispatch({ type: "creditEvaluationModel/updateState", payload: { searchParams: null } });
      dispatch({ type: 'creditEvaluationModel/getAllOrganizationItem', payload: { params: null } });
    },
    onOrganizationChooseRadioPageChange: (currentPage, pageSize) => {
      dispatch({ type: 'creditEvaluationModel/getAllOrganizationItem', payload: { currentPage, pageSize, params: searchParams } });
    },
    onOrganizationChooseRadioShowSizeChange: (currentPage, pageSize) => {
      dispatch({ type: 'creditEvaluationModel/getAllOrganizationItem', payload: { currentPage, pageSize, params: searchParams } });
    },
  };

  const onOrganizationChooseRadio = () => {
    dispatch({ type: "creditEvaluationModel/updateState", payload: { organizationChooseRadioVisible: true, searchParams: null } });
    dispatch({ type: 'creditEvaluationModel/getAllOrganizationItem', payload: {} });
  }

  const onExport = () => { dispatch({ type: "creditEvaluationModel/downloadOrganizational" }); }

  const onAssessment = (values, flag) => {
    setFieldsValue({ assessmentStatus: "credit_evaluation_midway" })
    useSpinFlag(true)
    useReferenceDataFlag(true)
    getEvaluation(values).then(res => {
      useSpinFlag(false)
      onGetDetail({ id: values.creditEvaluationId })
    })
  }

  const onCounterparty = () => {
    if (ownerShipInstitutionCode) {
      dispatch({ type: 'creditEvaluationModel/getAllCreditArchive', payload: { params: { affiliatedInstitution: ownerShipInstitutionCode } } });
    }
    dispatch({ type: 'creditEvaluationModel/updateState', payload: { counterpartyModalVisible: true, searchParams: null } })
  }

  const onUpload = (record) => {
    dispatch({
      type: "creditEvaluationModel/updateState", payload: { attachmentUploadModalVisible: true, masterDataCode: record.masterDataCode, }
    });
    dispatch({
      type: 'creditEvaluationModel/selectAttachmentModal', payload: {
        masterDataCode: record.masterDataCode, fileTypeCode: "credit_rating", basicId: getFieldsValue().id,
      }
    });
  }

  const creditFileManagementModalProps = {
    operateType: "view",
    flag: true,
    masterDataCode: creditEvaluationInfoData.masterDataCode,
    onCancel: () => useCreditFiles(false),
  }

  const attachmentUploadModalProps = {
    attachmentUploadModalVisible,
    attachmentUploadModalList,
    attachmentUploadModalLoading,
    fileType: "信用评估",
    fileTypeCode: "credit_rating",
    userInfo: JSON.parse(userInfo),
    masterDataCode,
    ownerShipInstitution,
    ownerShipInstitutionCode,
    basicId: getFieldsValue().id,
    onCancel: () => {
      dispatch({ type: "creditEvaluationModel/updateState", payload: { attachmentUploadModalVisible: false } });
    },
    onDownload: (values) => {
      dispatch({ type: "creditEvaluationModel/downloadFile", payload: values });
    },
    onDelete: (values) => {
      dispatch({
        type: "creditEvaluationModel/deleteFileById", payload: {
          params: values, data: { masterDataCode, fileTypeCode: "credit_rating", basicId: getFieldsValue().id, }
        }
      });
    },
    onUpload: (values) => {
      dispatch({ type: "creditEvaluationModel/updateState", payload: { attachmentUploadModalLoading: true } });
      dispatch({
        type: "creditEvaluationModel/uploadFile",
        payload: { params: values, data: { masterDataCode, fileTypeCode: "credit_rating", basicId: getFieldsValue().id, } }
      });
    }
  };

  const modelSelectionProps = {
    modelTotal, modelCurrentPage, modelPageSize, modelFilterModalerVisible, modelLoading, modelList: modelListData, selectedRowKeys, selectedRows,
    onPageChangeModal: (currentPage, pageSize) => {
      dispatch({ type: 'creditEvaluationModel/getAllpaymentRulesModel', payload: { currentPage, pageSize, params: searchParams } });
    },
    onShowSizeChangeModal: (currentPage, pageSize) => {
      dispatch({ type: 'creditEvaluationModel/getAllpaymentRulesModel', payload: { currentPage, pageSize, params: searchParams } });
    },
    onCancelModal: () => {
      dispatch({ type: "creditEvaluationModel/updateState", payload: { modelFilterModalerVisible: false, } });
    },
    onSearchModal: (searchParams) => {
      dispatch({ type: "creditEvaluationModel/updateState", payload: { searchParams } });
      dispatch({ type: 'creditEvaluationModel/getAllpaymentRulesModel', payload: { params: searchParams } });
    },
    onResetModal: () => {
      dispatch({ type: "creditEvaluationModel/updateState", payload: { searchParams: null } });
      dispatch({ type: 'creditEvaluationModel/getAllpaymentRulesModel', payload: { params: null } });
    },
    onChangeModel: (keys, selectedRows) => {
      dispatch({ type: 'creditEvaluationModel/updateState', payload: { selectedRows: selectedRows, selectedRowKeys: keys, }, })
    },
    onSaveModel: (key, row) => {
      if (!(key[0] == getFieldsValue().assessmentModelId && row[0].sign == getFieldsValue().sign)) {
        useIndicatorScoreResultVoList([])
      }
      setFieldsValue({
        assessmentModelId: key[0],
        sign: row[0].sign,
        assessmentModelName: row[0].modelName,
      })
      dispatch({ type: "creditEvaluationModel/updateState", payload: { modelFilterModalerVisible: false, } });
    },
  };

  const popoverContent = () => {
    return <div className={styles.popover_content}>
      <Button type="text" onClick={() => onUpload(getFieldsValue())} disabled={buttonDisabled}>附件上传及查看</Button>
      <Button type="text" onClick={() => useCreditFiles(true)} disabled={buttonDisabled}>信用档案查看</Button>
      <Button type="text" onClick={() => onExport()} disabled={buttonDisabled}>评估结果导出</Button>
    </div>
  }

  const onChooseModel = (rowRecord) => {
    dispatch({ type: 'creditEvaluationModel/getAllpaymentRulesModel', payload: {} });
    dispatch({ type: "creditEvaluationModel/updateState", payload: { modelFilterModalerVisible: true, selectedRowKeys: [rowRecord], } });
  }

  const onBeginAssess = () => {
    let prop = getFieldsValue()
    if (prop.assessmentModelId && prop.assessmentModelName) {
      getCreditDataByCompanyName({ companyName: prop.counterpartyName }).then(item => {
        if (item.data == 1) {
          onCloneBeginAssess(prop)
        } else if (item.data == 0) {
          Modal.confirm({
            icon: <ExclamationCircleOutlined />,
            content: '该客户征信数据同步不完整，请确认是否继续',
            okText: '是',
            cancelText: '否',
            onOk: () => onCloneBeginAssess(prop),
            onCancel: () => {
              message.warning('请重新抽取征信数据或反馈生产管理部！')
            }
          })
        }
      })
    } else {
      message.warning('未匹配到模型，请调用征信数据后重试！');
    }
  }

  const onCloneBeginAssess = (prop) => {
    getHistoryDataLastTime({ companyName: prop.counterpartyName }).then(res => {
      if (res.data.lastTime) {
        Modal.confirm({
          icon: <ExclamationCircleOutlined />,
          content: '最近调取记录日期为' + moment(res.data.lastTime).format('YYYY-MM-DD') + '，请确认是否开始评估',
          okText: '是',
          cancelText: '否',
          onOk: () => {
            let list = []
            indicatorScoreResultVoList.forEach(item => {
              list = list.concat(item.indicatorScoreResultList)
            })
            onAssessment({ creditEvaluationId: prop.id, flag: 1, type: 0, })
          },
        })
      } else {
        message.warning('未匹配到模型，请调用征信数据后重试！');
      }
    })
  }

  const onReferenceDataCall = (prop) => {
    useSpinFlag('true')
    getCreditData({
      companyName: prop.counterpartyName, masterDataCode: prop.masterDataCode, affiliatedInstitutionCode: prop.affiliatedInstitution,
      creditEvaluationId: prop.id
    }).then(res => {
      useSpinFlag(false)
      if (res.data && res.data.normalModelId) {
        setFieldsValue({ assessmentModelId: res.data.normalModelId, assessmentModelName: res.data.normalModelName, sign: res.data.sign })
        onAdd()
      }
    })
  }

  const debounceAddFun = debounce(onAdd, 1000)
  const debounceAssessFun = debounce(onBeginAssess, 1000)

  return (
    <div>
      <Spin tip={spinFlag === 'true' ? '征信数据调取中，请稍后！' : spinFlag === 'add' ? null : "客户信用评估中，请稍后！"} spinning={spinFlag}
        indicator={<div style={{ height: "50px", width: "37px", top: "40%", margin: "-30px" }}>
          <img src={img}></img>
        </div>}>
        {
          creditFiles && (<CreditFileManagementModal {...creditFileManagementModalProps} />)
        }
        {
          !creditFiles && (<>
            <Card style={{ marginBottom: "16px" }}>
              <div className={styles.toolbarText} style={{ marginBottom: "0" }}>
                <div>信用评估申请</div>
                <div style={{ display: 'flex' }}>
                  <Button style={{ borderRight: 'none' }} onClick={() => onReferenceDataCall(getFieldsValue())}
                    disabled={buttonDisabled || referenceDataFlag}>征信数据调取</Button>
                  <Popover content={popoverContent} trigger="hover" placement="bottomRight">
                    <Button type="defalue"><EllipsisOutlined /></Button>
                  </Popover>
                  <Button style={{ margin: '0 15px' }} onClick={() => {
                    onCancel()
                    dispatch({
                      type: "creditEvaluationModel/updateState", payload: {
                        idFlag: null, modelFlag: false, detailList: {}, historicalList: [], historicalPList: [], historicalTotal: 0, historicalCurrentPage: 0,
                        historicalPageSize: 0,
                      }
                    });
                  }} >返回</Button>
                  <Button style={{ marginRight: '15px' }} onClick={() => { useSpinFlag('add'); debounceAddFun() }} disabled={(operateType === "view" && menuProcessing("_edit")) || disabledFlag}>保存</Button>
                  <Button type="primary" disabled={(operateType === "view" && menuProcessing("_edit")) || !(getFieldsValue().id && !disabledFlag)}
                    onClick={debounceAssessFun}>开始评估</Button>
                </div>
              </div>
            </Card>
            <Card>
              <Divider orientation="left">
                <span className={styles.textDivider}>
                  <i></i>
                  基础信息
                </span>
              </Divider>
              <Form form={form} layout={"vertical"}>
                <Row gutter={20}>
                  <Col span={0}>
                    <FormItem label="交易方名称" name={"id"} >
                      <Input />
                    </FormItem>
                  </Col>
                  <Col span={0}>
                    <FormItem label="创建人" name={"basicId"}>
                      <Input placeholder="请输入创建人" />
                    </FormItem>
                  </Col>
                  <Col span={0}>
                    <FormItem label="交易方名称" name={"masterDataCode"} rules={[{ required: true, message: '请选择交易方名称' }]}>
                      <Input />
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="归属机构" name={"affiliatedInstitutionName"} rules={[{ required: true, message: '请输入归属机构' }]}>
                      <Search autoComplete="off" onSearch={() => onOrganizationChooseRadio()} onClick={() => onOrganizationChooseRadio()}
                        disabled={(operateType === "view" && menuProcessing("_edit")) || creditEvaluationFlagTrue || disabledFlag} />
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="交易方名称" name={"counterpartyName"} rules={[{ required: true, message: '请选择交易方名称' }]}>
                      <Search autoComplete="off" onSearch={() => onCounterparty()} onClick={() => onCounterparty()}
                        disabled={(operateType === "view" && menuProcessing("_edit")) || creditEvaluationFlagTrue || disabledFlag} />
                    </FormItem>
                  </Col>
                  <Col span={0}>
                    <FormItem label="归属机构" name={"affiliatedInstitution"} rules={[{ required: true, message: '请输入归属机构' }]}>
                      <Input />
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="状态" name={"assessmentStatus"}>
                      <Select disabled>
                        {examinationApprovalStatusOptions}
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span={0}>
                    <FormItem label="评估模型" name={"assessmentModelId"}>
                      <Input placeholder="请输入评估模型" />
                    </FormItem>
                  </Col>
                  <Col span={0}>
                    <FormItem label="评估模型" name={"sign"}>
                      <Input placeholder="请输入评估模型" />
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="评估模型" name={"assessmentModelName"}>
                      <Search autoComplete="off" onSearch={() => onChooseModel("" + getFieldsValue().assessmentModelId + getFieldsValue().sign)}
                        disabled={(operateType === "view" && menuProcessing("_edit")) || menuProcessing("_modelSelection") || disabledFlag}
                        onClick={() => onChooseModel("" + getFieldsValue().assessmentModelId + getFieldsValue().sign)} onChange={(e) => {
                          if (!e.target.value) { setFieldsValue({ assessmentModelId: '', sign: '', assessmentModelName: '', }) }
                        }} />
                    </FormItem>
                  </Col>
                  <Col span={0}>
                    <FormItem label="创建人" name={"createId"}>
                      <Input placeholder="请输入创建人" />
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="创建人" name={"createName"}>
                      <Input placeholder="请输入创建人" disabled />
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="评估时间" name={"createTime"}>
                      <Input placeholder="请输入评估时间" disabled />
                    </FormItem>
                  </Col>
                </Row>
              </Form>
              <Divider orientation="left">
                <span className={styles.textDivider}>
                  <i></i>
                  评分模型信息
                </span>
              </Divider>
              <div style={{ textAlign: "center", color: "#489CC9", marginBottom: "20px" }}>信用评估结果</div>
              <Row gutter={20} >
                <Col span={6}>
                  <div className={styles.modelScoreResult}>
                    <p>客户信用评估综合得分</p>
                    <p style={{ color: "#489CC9", fontSize: "24px", height: "38px" }}>{
                      modelScoreResult.evaluationScore ? reservedDecimalPlace(modelScoreResult.evaluationScore, 2, true) : 0.00}</p>
                  </div>
                </Col>
                <Col span={6}>
                  <div className={styles.modelScoreResult}>
                    <p>客户信用评估等级</p>
                    <p style={{ color: "#489CC9", fontSize: "24px", height: "38px" }}>{modelScoreResult.evaluationLevel}</p>
                  </div>
                </Col>
                <Col span={6}>
                  <div className={styles.modelScoreResult}>
                    <p>模型建议授信额度（元）（CNY）</p>
                    <p style={{ color: "#489CC9", fontSize: "24px", height: "38px" }}>{modelScoreResult.creditLimit ?
                      formatNoFixed(reservedDecimalPlace(modelScoreResult.creditLimit, 2)) : 0}</p>
                  </div>
                </Col>
                <Col span={6}>
                  <div className={styles.modelScoreResult}>
                    <p>模型建议最长授信账期（天）</p>
                    <p style={{ color: "#489CC9", fontSize: "24px", height: "38px" }}>{modelScoreResult.maximumCreditPeriod}</p>
                  </div>
                </Col>
              </Row>
              {
                indicatorScoreResultVoList.map((item, index) => (
                  <div key={index}>
                    <div style={{ color: "#489CC9", textAlign: "center", margin: "20px 0" }}>
                      <span className={styles.modelIndex}>{index < 9 ? "0" + (index + 1) : index + 1}</span>
                      <span style={{ padding: "0 10px" }}>{item.modelName}</span>
                      <span>{valueToPercent(item.modelWeight)}%</span>
                    </div>
                    <Table
                      size="small"
                      bordered
                      locale={{ emptyText }}
                      columns={informationEvaluationIndex}
                      dataSource={item.indicatorScoreResultList}
                      pagination={false}
                      scroll={{ y: 500 }}
                      rowKey={record => record.indicatorId}
                    />
                  </div>
                ))
              }
              <Divider orientation="left">
                <span className={styles.textDivider}>
                  <i></i>
                  评估结果调整
                </span>
              </Divider>
              <Table
                size="small"
                locale={{ emptyText }}
                bordered
                columns={adjustmentEvaluationResults}
                dataSource={indicatorAdjustmentList}
                pagination={false}
                rowKey={record => record.indicatorId}
              />
              <Divider orientation="left">
                <span className={styles.textDivider}>
                  <i></i>
                  历史评估结果
                </span>
              </Divider>
              <Table
                size="small"
                bordered
                locale={{ emptyText }}
                columns={historicalAssessmentResults}
                dataSource={historicalList}
                pagination={false}
                scroll={{ y: 500 }}
                loading={historicalLoading ? { indicator: <div><img src={img}></img></div> } : false}
                rowKey={record => record.creditEvaluationId}
              />
              <TablePagination {...tablePaginationProps} />
              <Divider orientation="left">
                <span className={styles.textDivider}>
                  <i></i>
                  历史评估数据
                </span>
              </Divider>
              <div style={{ width: "100%", height: "300px" }}>
                <div id="history" style={styleFlag}></div>
              </div>
            </Card>
          </>)
        }

        <CounterpartyChooseRadio {...counterpartyChooseProps} />
        <OrganizationChooseRadio {...organizationChooseRadioProps} />
        <AttachmentUploadModal {...attachmentUploadModalProps} />
        <ModelSelection {...modelSelectionProps} />
      </Spin>
    </div >
  );
}

function mapStateToProps({ globalModel, creditEvaluationModel }) {
  return { globalModel, creditEvaluationModel };
}

export default connect(mapStateToProps)(CreditEvaluationCreate);
